<template>
  <header class="navbar">
    <div class="navbar-container">
      <div class="navbar-logo">
        <h1>校园二手书店</h1>
      </div>
      <div class="navbar-search">
        <input type="text" placeholder="搜索书籍..." v-model="searchQuery" @keyup.enter="search" />
        <button @click="search">搜索</button>
      </div>
      <nav class="navbar-links">
        <router-link to="/">首页</router-link>
        <template v-if="isLoggedIn">
          <router-link to="/publish">发布书籍</router-link>
          <router-link to="/my-books">我的书籍</router-link>
          <router-link to="/messages">消息</router-link>
          <div class="user-avatar-container">
            <div class="user-menu-trigger" @click="toggleUserMenu">
              <img :src="avatarUrl || '/avatar.PNG'" alt="用户头像" class="user-avatar" @error="handleImageError" />
              <span class="username">{{ username }}</span>
            </div>
            <div class="user-menu" v-if="showUserMenu">
              <router-link to="/user" class="menu-item">个人中心</router-link>
              <router-link to="/my-books" class="menu-item">我的书籍</router-link>
              <router-link to="/transactions" class="menu-item">交易记录</router-link>
              <router-link to="/my-reports" class="menu-item">我的举报</router-link>
              <div class="menu-divider"></div>
              <button @click="logout" class="menu-item logout">退出登录</button>
            </div>
          </div>
        </template>
        <template v-else>
          <router-link to="/login" class="btn-login">登录/注册</router-link>
        </template>
      </nav>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api/apiClient'
import fileUtil from '@/utils/fileUtil'

const router = useRouter()
const searchQuery = ref('')
const isLoggedIn = ref(false)
const username = ref('')
const showUserMenu = ref(false)
const avatarUrl = ref(null)
const isAvatarLoading = ref(false)

// 从localStorage中获取缓存的头像URL
const getCachedAvatarUrl = () => {
  const cachedAvatar = localStorage.getItem('cachedAvatarUrl')
  return cachedAvatar || null
}

// 检查头像缓存是否过期（超过1小时）
const isAvatarCacheExpired = () => {
  const cacheTimestamp = localStorage.getItem('avatarCacheTime')
  if (!cacheTimestamp) return true
  
  const cacheTime = parseInt(cacheTimestamp)
  const currentTime = new Date().getTime()
  // 缓存超过1小时（3600000毫秒）视为过期
  return (currentTime - cacheTime) > 3600000
}

// 缓存头像URL到localStorage
const cacheAvatarUrl = (url) => {
  if (url) {
    localStorage.setItem('cachedAvatarUrl', url)
    // 同时保存缓存时间
    localStorage.setItem('avatarCacheTime', new Date().getTime().toString())
  }
}

// 获取用户头像
const fetchUserAvatar = async () => {
  isAvatarLoading.value = true
  try {
    // 在fileUtil中已经可能抛出异常，这里添加额外的错误处理
    try {
      const result = await fileUtil.downloadAvatar()
      
      // 处理特殊的noAvatar标记
      if (result && result.noAvatar === true) {
        console.log('检测到无头像标记，使用默认头像')
        avatarUrl.value = '' // 使用默认头像
        return
      }
      
      if (result && result.success) {
        avatarUrl.value = result.imageUrl
        // 保存头像URL到缓存中
        cacheAvatarUrl(result.imageUrl)
        console.log('头像获取成功并缓存:', result.imageUrl)
      } else {
        console.warn('导航栏获取头像失败:', result?.message)
        // 服务器返回失败但不抛出异常的情况
        avatarUrl.value = '' // 设置为空字符串，使用默认头像
      }
    } catch (innerError) {
      // 捕获API调用抛出的异常
      console.warn('导航栏获取头像API调用失败:', innerError.message)
      avatarUrl.value = '' // 设置为空字符串，使用默认头像
    }

    // 如果到此处头像URL仍为空，尝试使用缓存
    if (!avatarUrl.value) {
      const cachedUrl = getCachedAvatarUrl()
      if (cachedUrl) {
        console.log('使用缓存的头像:', cachedUrl)
        avatarUrl.value = cachedUrl
      }
    }
  } catch (error) {
    // 这里捕获其他可能的错误
    console.error('导航栏头像处理出错:', error)
    avatarUrl.value = '' // 确保在任何错误情况下avatarUrl有值
  } finally {
    isAvatarLoading.value = false
  }
}

// 强制更新登录状态
const forceUpdateLoginStatus = () => {
  // 重新检查登录状态
  const token = localStorage.getItem('token')
  const storedLoginStatus = localStorage.getItem('isLoggedIn') === 'true'
  
  console.log('强制更新登录状态, 当前token:', token ? '存在' : '不存在', '存储的登录状态:', storedLoginStatus)
  
  // 如果有token但isLoggedIn不是true，修正它
  if (token && !storedLoginStatus) {
    console.log('检测到token存在但登录状态不正确，修正为已登录')
    localStorage.setItem('isLoggedIn', 'true')
    isLoggedIn.value = true
    
    // 更新用户名 - 从多个来源尝试获取用户名
    try {
      // 尝试从localStorage中的user对象获取
      const userStr = localStorage.getItem('user')
      if (userStr) {
        const userData = JSON.parse(userStr)
        if (userData && userData.username) {
          username.value = userData.username
          console.log('从用户对象获取到用户名:', username.value)
          // 同步到username键，确保一致性
          localStorage.setItem('username', username.value)
        }
      }
    } catch (e) {
      console.error('解析用户数据失败:', e)
    }
    
    // 如果上面的方法没有获取到用户名，则使用localStorage中的username或默认值
    if (!username.value) {
      username.value = localStorage.getItem('username') || '用户'
      console.log('使用localStorage中的username或默认值:', username.value)
    }
    
    // 获取头像
    fetchUserAvatar()
    return true
  }
  
  // 如果没有token但isLoggedIn是true，修正它
  if (!token && storedLoginStatus) {
    console.log('检测到token不存在但登录状态为已登录，修正为未登录')
    localStorage.setItem('isLoggedIn', 'false')
    isLoggedIn.value = false
    return true
  }
  
  // 保持登录状态同步
  isLoggedIn.value = storedLoginStatus
  return false
}

onMounted(() => {
  // 强制更新登录状态
  forceUpdateLoginStatus()
  
  if (isLoggedIn.value) {
    console.log('用户已登录，初始化用户信息')
    
    // 尝试从多个来源获取用户名
    try {
      // 首先尝试从localStorage中的user对象获取
      const userStr = localStorage.getItem('user')
      if (userStr) {
        const userData = JSON.parse(userStr)
        if (userData && userData.username) {
          username.value = userData.username
          console.log('从用户对象获取到用户名:', username.value)
          // 同步到username键，确保一致性
          localStorage.setItem('username', username.value)
        }
      }
    } catch (e) {
      console.error('解析用户数据失败:', e)
    }
    
    // 如果上面的方法没有获取到用户名，则使用localStorage中的username
    if (!username.value) {
      username.value = localStorage.getItem('username') || '用户'
      console.log('从localStorage中获取用户名:', username.value)
    }
    
    // 先检查并使用缓存的头像
    const cachedUrl = getCachedAvatarUrl()
    if (cachedUrl) {
      avatarUrl.value = cachedUrl
      console.log('使用缓存的头像URL:', cachedUrl)
    }
    
    // 检查是否有头像更新标记
    const avatarUpdated = localStorage.getItem('avatarUpdated') === 'true'
    if (avatarUpdated) {
      // 清除标记并立即获取最新头像
      localStorage.removeItem('avatarUpdated')
      fetchUserAvatar()
    } else {
      // 如果没有缓存或者缓存已过期，再获取头像
      if (!cachedUrl || isAvatarCacheExpired()) {
        fetchUserAvatar()
      }
    }
  } else {
    console.log('用户未登录')
  }
  
  // 在页面加载后0.5秒检查一次登录状态，处理潜在的登录刚完成的情况
  setTimeout(() => {
    if (forceUpdateLoginStatus()) {
      console.log('初始延迟检查发现并修正了登录状态')
    }
  }, 500)
  
  document.addEventListener('click', closeMenuOnClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeMenuOnClickOutside)
})

// 处理图片加载错误
const handleImageError = (event) => {
  console.warn('头像加载失败，使用默认头像')
  event.target.src = '/avatar.png'
  event.target.onerror = null
}

const search = () => {
  if (searchQuery.value.trim()) {
    // 执行搜索跳转，将关键字作为查询参数
    router.push({ 
      path: '/search', 
      query: { q: searchQuery.value.trim() }
    })
    // 清空搜索框
    searchQuery.value = ''
  }
}

const toggleUserMenu = (event) => {
  event.stopPropagation()
  showUserMenu.value = !showUserMenu.value
}

const closeMenuOnClickOutside = (event) => {
  if (showUserMenu.value && !event.target.closest('.user-menu') && !event.target.closest('.user-menu-trigger')) {
    showUserMenu.value = false
  }
}

const logout = async () => {
  try {
    await api.user.logout()
    // 清除所有相关的localStorage项
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('userRole')
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
    localStorage.removeItem('token')
    localStorage.removeItem('cachedAvatarUrl')
    localStorage.removeItem('avatarCacheTime')
    
    // 清除头像相关状态
    avatarUrl.value = null
    isLoggedIn.value = false
    router.push('/login')
  } catch (error) {
    console.error('登出失败:', error)
  }
}

// 检查登录状态的辅助函数
const checkLoginStatus = () => {
  // 每次调用时重新检查localStorage
  const loginStatus = localStorage.getItem('isLoggedIn') === 'true'
  const token = localStorage.getItem('token')
  
  // 仅做日志，不修改状态
  if (loginStatus !== isLoggedIn.value) {
    console.log('检测到登录状态变更:', loginStatus ? '已登录' : '未登录', '但组件状态为:', isLoggedIn.value ? '已登录' : '未登录')
  }
  
  // 矫正登录状态
  if (token && !loginStatus) {
    console.log('存在token但登录状态为未登录，修正')
    localStorage.setItem('isLoggedIn', 'true')
    if (!isLoggedIn.value) {
      isLoggedIn.value = true
      // 更新用户名和头像
      try {
        // 尝试从localStorage中的user对象获取用户名
        const userStr = localStorage.getItem('user')
        if (userStr) {
          const userData = JSON.parse(userStr)
          if (userData && userData.username) {
            username.value = userData.username
            console.log('从用户对象获取到用户名:', username.value)
            // 同步到username键，确保一致性
            localStorage.setItem('username', username.value)
          }
        }
      } catch (e) {
        console.error('解析用户数据失败:', e)
      }
      
      // 如果上面的方法没有获取到用户名，则使用localStorage中的username
      if (!username.value) {
        username.value = localStorage.getItem('username') || '用户'
        console.log('从localStorage中获取用户名:', username.value)
      }
      
      fetchUserAvatar()
    }
  } else if (!token && loginStatus) {
    console.log('不存在token但登录状态为已登录，修正')
    localStorage.setItem('isLoggedIn', 'false')
    if (isLoggedIn.value) {
      isLoggedIn.value = false
    }
  } else if (loginStatus !== isLoggedIn.value) {
    // 同步组件状态和localStorage状态
    isLoggedIn.value = loginStatus
    // 如果刚登录，获取用户信息
    if (isLoggedIn.value) {
      // 尝试从多个来源获取用户名
      try {
        // 首先尝试从localStorage中的user对象获取
        const userStr = localStorage.getItem('user')
        if (userStr) {
          const userData = JSON.parse(userStr)
          if (userData && userData.username) {
            username.value = userData.username
            console.log('从用户对象获取到用户名:', username.value)
            // 同步到username键，确保一致性
            localStorage.setItem('username', username.value)
          }
        }
      } catch (e) {
        console.error('解析用户数据失败:', e)
      }
      
      // 如果上面的方法没有获取到用户名，则使用localStorage中的username
      if (!username.value) {
        username.value = localStorage.getItem('username') || '用户'
      }
      
      fetchUserAvatar()
    }
  }
  
  // 始终检查用户名是否需要更新
  if (isLoggedIn.value) {
    // 尝试从localStorage中的user对象获取最新用户名
    try {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        const userData = JSON.parse(userStr)
        if (userData && userData.username && userData.username !== username.value) {
          username.value = userData.username
          console.log('更新用户名为:', username.value)
          // 同步到username键，确保一致性
          localStorage.setItem('username', username.value)
        }
      }
    } catch (e) {
      // 忽略解析错误
    }
  }
}

// 每2秒检查一次登录状态
const loginStatusInterval = setInterval(checkLoginStatus, 2000)

// 在组件卸载前清除定时器
onBeforeUnmount(() => {
  document.removeEventListener('click', closeMenuOnClickOutside)
  clearInterval(loginStatusInterval)
})
</script>

<style scoped>
.navbar {
  background-color: #f8f9fa;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 2rem;
  max-width: 1400px;
  margin: 0 auto;
}

.navbar-logo h1 {
  margin: 0;
  font-size: 1.5rem;
  color: #3b82f6;
  white-space: nowrap;
}

.navbar-search {
  display: flex;
  gap: 0.5rem;
  flex: 1;
  max-width: 500px;
  margin: 0 2rem;
}

.navbar-search input {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 100%;
}

.navbar-search button {
  padding: 0.5rem 1rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
}

.navbar-search button:hover {
  background-color: #2563eb;
}

.navbar-links {
  display: flex;
  gap: 1.5rem;
  align-items: center;
}

.navbar-links a {
  text-decoration: none;
  color: #4b5563;
  font-weight: 500;
  white-space: nowrap;
}

.navbar-links a:hover, .navbar-links a.router-link-active {
  color: #3b82f6;
}

.user-avatar-container {
  margin-left: 1rem;
  position: relative;
}

.user-avatar-link {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #3b82f6;
}

@media (max-width: 992px) {
  .navbar-container {
    flex-wrap: wrap;
    justify-content: space-between;
  }
  
  .navbar-search {
    order: 3;
    margin: 0.75rem 0 0;
    max-width: 100%;
    width: 100%;
  }
  
  .navbar-links {
    overflow: visible;
    padding-bottom: 0.5rem;
    margin-left: auto;
    position: relative;
  }

  .user-avatar-container {
    position: static;
  }

  .user-menu {
    position: absolute;
    right: 0;
    top: calc(100% - 0.5rem);
    margin-top: 0;
  }
}

@media (max-width: 768px) {
  .navbar-links {
    gap: 1rem;
    font-size: 0.9rem;
  }
  
  .user-menu {
    width: 180px;
    right: 0;
  }
}

.user-menu-trigger {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
}

.username {
  margin-left: 0.5rem;
  font-weight: 500;
}

.user-menu {
  position: absolute;
  top: 100%;
  right: 0;
  width: 200px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  margin-top: 0.5rem;
  z-index: 1000;
  transform: translateX(0);
}

.menu-item {
  display: block;
  padding: 0.75rem 1rem;
  color: #4b5563;
  text-decoration: none;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #f3f4f6;
}

.menu-divider {
  height: 1px;
  background-color: #e5e7eb;
  margin: 0.5rem 0;
}

.menu-item.logout {
  color: #ef4444;
  width: 100%;
  text-align: left;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 1rem;
}

.btn-login {
  background-color: #3b82f6;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.btn-login:hover {
  background-color: #2563eb;
  text-decoration: none;
}

/* 让菜单项可点击 */
.menu-item {
  cursor: pointer;
}
</style> 